package com.chuangmei.com.arindoorlocationsystem.ar;

/**
 * 项目名称：ARIndoorLocationSystem
 * 类描述：录制屏幕与保存视频实现服务
 * 创建人：LuoHao
 * 创建时间：2018/4/13 14:11
 * 修改人：LuoHao
 * 修改时间：2018/4/13 14:11
 * 修改备注：
 */


import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.os.Binder;
import android.os.Build;
import android.os.HandlerThread;
import android.os.IBinder;
import android.util.Log;

import com.chuangmei.com.arindoorlocationsystem.utils.Constant;
import com.chuangmei.com.arindoorlocationsystem.utils.TimeUtils;

import java.io.IOException;

/**
 * 录屏处理服务
 */
public class RecordService extends Service {
    private MediaProjection mediaProjection;
    private MediaRecorder mediaRecorder;
    private VirtualDisplay virtualDisplay;

    private boolean running;
    private int width = 720;
    private int height = 1080;
    private int dpi;

    public static String videoSaveName;
    private ServiceCallBack serviceCallBack;

    @Override
    public IBinder onBind(Intent intent) {
        return new RecordBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread serviceThread = new HandlerThread("service_thread",
                android.os.Process.THREAD_PRIORITY_BACKGROUND);
        serviceThread.start();
        running = false;
        mediaRecorder = new MediaRecorder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 填充媒体对象，在停止时回调接口
     *
     * @param project
     */

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void setMediaProject(MediaProjection project) {
        mediaProjection = project;
        mediaProjection.registerCallback(new MediaProjection.Callback() {
            @Override
            public void onStop() {
                super.onStop();
                serviceCallBack.onStop(Constant.dir_video, videoSaveName);
            }
        }, null);
    }

    public boolean isRunning() {
        return running;
    }

    /**
     * 填充截屏，屏幕属性
     *
     * @param width
     * @param height
     * @param dpi
     */
    public void setScreenSize(int width, int height, int dpi) {
        this.width = width;
        this.height = height;
        this.dpi = dpi;
    }

    /**
     * 开始录屏逻辑
     *
     * @return
     */
    public boolean startRecord() {
        if (mediaProjection == null || running) {
            return false;
        }
        videoSaveName = TimeUtils.getStringToday() + ".mp4";
        initRecorder();
        createVirtualDisplay();

        mediaRecorder.start();
        serviceCallBack.onStart();

        running = true;
        return true;
    }

    /**
     * 停止录屏，合成MP4文件，释放资源
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public boolean stopRecord() {
        if (!running) {
            return false;
        }
        running = false;
        mediaRecorder.stop();
        mediaRecorder.reset();
        virtualDisplay.release();
        mediaProjection.stop();

        return true;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void createVirtualDisplay() {
        virtualDisplay = mediaProjection.createVirtualDisplay("MainScreen", width, height, dpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mediaRecorder.getSurface(), null, null);
    }

    /**
     * 初始化录屏参数
     */
    private void initRecorder() {
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setOutputFile(Constant.dir_video + videoSaveName);
        mediaRecorder.setVideoSize(width, height);
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//HEVC与H264均可，HEVC编码出的视频略小
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setVideoEncodingBitRate(1024 * 1024);
        mediaRecorder.setVideoFrameRate(30);
        try {
            mediaRecorder.prepare();
            Log.d("luohao", "准备就绪" + Constant.dir_video + videoSaveName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 传入状态回调接口
     *
     * @param serviceCallBack
     */
    public void recordingEndListener(ServiceCallBack serviceCallBack) {
        this.serviceCallBack = serviceCallBack;
    }

    public class RecordBinder extends Binder {
        public RecordService getRecordService() {
            return RecordService.this;
        }
    }
}